import {
  BuilderComponentPlugin, ICodeStruct, ChunkType,
  BuilderComponentPluginFactory, FileType,
} from '../../../types';
import { COMMON_CHUNK_NAME } from '../../../const/generator';

export interface PluginConfig {
  fileType?: string;
  nodeTypeMapping?: Record<string, string>;
}

const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = () => {
  const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
    const next: ICodeStruct = {
      ...pre,
    };
    const { tolerateEvalErrors = true, evalErrorsHandler = '' } = next.contextData;

    next.chunks.push({
      type: ChunkType.STRING,
      fileType: FileType.JSX,
      name: COMMON_CHUNK_NAME.CustomContent,
      content: [
        tolerateEvalErrors &&
        `
          function __$$eval(expr) {
            try {
              return expr();
            } catch (error) {
              ${evalErrorsHandler}
            }
          }

          function __$$evalArray(expr) {
            const res = __$$eval(expr);
            return Array.isArray(res) ? res : [];
          }
        `,
        `
        function __$$createChildContext(oldContext, ext) {
          const childContext = {
            ...oldContext,
            ...ext,
          };
          childContext.__proto__ = oldContext;
          return childContext;
        }
        `,
      ].filter(Boolean).join('\n'),
      linkAfter: [COMMON_CHUNK_NAME.FileExport],
    });
    return next;
  };
  return plugin;
};

export default pluginFactory;
